<!--
 * @Author: Li Zengkun
 * @Date: 2022-09-27 22:02:58
 * @LastEditors: Li Zengkun
 * @LastEditTime: 2022-09-27 22:44:45
 * @Description: 
-->
<template>
  <div>
    <el-upload
      :file-list="props.fileList"
      :action="props.action"
      :headers="headers"
      :limit="6"
      list-type="picture-card"
      :before-upload="handleBeforeUpload"
      :on-success="handleSliderSuccess"
      :on-exceed="handleSliderExceed"
      :before-remove="handleSliderBeforeRemove"
      :on-error="handleUploadError"
      :on-preview="handleCardPreview"
    >
      <el-icon class="avatar-uploader-icon"><Plus /></el-icon>
    </el-upload>
    <!-- 图片预览 -->
    <el-dialog width="50%" v-model="dialogVisible">
      <img :src="dialogImageUrl" style="width:100%" alt="" />
    </el-dialog>
  </div>
</template>
 
<script setup>
import { ref, reactive } from "vue";
import {upload} from '@/api'

const props = defineProps({
  modelValue: {
    type: String,
  },
  action: {
    type: String,
    required: true,
  },
  fileList: {
    type: Array,
  },
});
const emit = defineEmits(['update:modelValue'])

const dialogImageUrl = ref("");
const dialogVisible = ref(false);
const headers = {
  Authorization: `Bearer ${sessionStorage.token}`,
};

// 上传图片校验
const handleBeforeUpload = (file) => {
  let reg = /^image\/(jpe?g|png)$/;
  const isImg = reg.test(file.type);
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isImg) {
    ElMessage.error("上传图片只能是 JPG / PNG 格式");
  }
  if (!isLt2M) {
    ElMessage.error("上传图片大小不能超过 2M");
  }
  return isImg && isLt2M;
};
// 预览
const handleCardPreview = (file)=>{
    console.log(file);
    console.log(dialogImageUrl.value);
    dialogVisible.value = true
    dialogImageUrl.value = file.response.src
}
// 上传成功
const handleSliderSuccess = (res, file,fileList) => {
    if(res.status){
        let data = convertFileList(fileList)
        emit('update:modelValue',data)
    }
};
// 超出限制
const handleSliderExceed = (files,fileList)=>{
    ElMessage.error(`当前限制选择 6 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
}

// 上传失败
const handleUploadError = ({ status, message }, file, fileList) => {
  let { msg } = JSON.parse(message);
  switch (status) {
    case 401:
      ElMessage.error("401,token失效，请重新登录");
      break;

    case 400:
      ElMessage.error(`400,${msg}`);
      break;

    default:
      ElMessage.error(`${status},${msg}`);
      break;
  }
};

// 删除图片
const handleSliderBeforeRemove = async (file,fileList) => {
    let src = file.response.src
    let {status} = await upload.remove({src})
    if(status){
        let i = fileList.findIndex(item=>item.url == src)
        let copy = [...fileList]
        copy.splice(i,1)
        let data = convertFileList(copy)
        emit('update:modelValue',data)
        return true
    }else{
        return false
    }
};

// 转换数据格式
const convertFileList = (fileList)=>{
    let res = []
    fileList.forEach(element => {
        res.push(element.response.src)
    });
    return res.toString()
}
</script>

<style lang='less' scoped>
</style>

